package faf.web;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;

import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.view.RedirectView;

import faf.business.AdministrationManager;
import faf.entities.Account;
import faf.web.data.SearchAccountsForm;

public class AdministrationController extends SimpleFormController {

	AdministrationManager manager;

	public void setManager(AdministrationManager manager) {
		this.manager = manager;
	}

	protected Object formBackingObject(HttpServletRequest request)
			throws ServletException {
		SearchAccountsForm searchAccountsForm = new SearchAccountsForm();
		Account loggedAccount = (Account) request.getSession().getAttribute("user");
		List<Account> accounts = manager.listAccounts();
		request.setAttribute("listAccounts", accounts);
		request.setAttribute("loggedUser", loggedAccount);
		request.setAttribute("appPath",request.getContextPath().substring(1));
		
		return searchAccountsForm;
	}
	
	public ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		
		SearchAccountsForm searchAccountsForm = (SearchAccountsForm) command;
		Account loggedAccount = (Account) request.getSession().getAttribute("user");
		if (loggedAccount == null) {
			return new ModelAndView(new RedirectView("login.htm?nexturl=administration.htm"));
		}
		if (errors.hasErrors()) {
			List<Account> accounts = manager.listAccounts();
			request.setAttribute("listAccounts", accounts);
			Map<Object, Object> model = new HashMap<Object, Object>();
			model.put("accounts", accounts);
			model.put("loggedUser", loggedAccount);
			model.put("searchAccountsForm", searchAccountsForm);
			return new ModelAndView("administration", model);
			
		}else {
			String firstname = searchAccountsForm.getLastname();
			String mail = searchAccountsForm.getMail();
			List<Account> accounts = manager.findAccounts(firstname, mail);
			request.setAttribute("listAccounts", accounts);
			Map<Object, Object> model = new HashMap<Object, Object>();
			model.put("accounts", accounts);
			model.put("loggedUser", loggedAccount);
			model.put("searchAccountsForm", searchAccountsForm);
			return new ModelAndView("administration", model);
		}
	}
}
